const {authenticate, create, find} = require("../services/user");

const handleSignup = async (req, res, next)=>{
    try{
        const {name,email,password} = req.body;
        const user = await find({email});
        if (user){
            throw new Error("User already exists");
        }
        const {token} = await create({name,email,password});
        res.json({token});
    }catch (e){
        next(e);
    }
};
const handleLogin = async (req, res, next)=>{
    try{
        const {email,password} = req.body;
        const user = await find({email});
        if (!user){
            throw new Error("User not found");
        }
        const {token} = await authenticate({email,password});
        res.json({token});
    }catch (e){
        next(e);
    }
};
module.exports = {
    handleSignup,
    handleLogin
}